/*!
 * Bolg main JS.
 * 
 * @since: 1.0.0 2017/3/9
 * @author Way Lau <https://waylau.com>
 */
"use strict";
//# sourceURL=main.js
 
// DOM 加载完再执行
$(function() {
	
	var _pageSize; // 存储用于搜索
	
	// 根据用户名、页面索引、页面大小获取用户列表
	function getCommentsByAuthor(pageIndex, pageSize) {
		 $.ajax({ 
			 url: "/comments",
			 contentType : 'application/json',
			 data:{
				 "async":true, 
				 "pageIndex":pageIndex,
				 "pageSize":pageSize,
				 "author":$("#searchName").val()
			 },
			 success: function(data){
				 $("#mainContainer").html(data);
		     },
		     error : function() {
		         alert("error");
		     }
		 });
	}
	
	// 分页
//	$.tbpage("#mainContainer", ".page-link", function (pageIndex, pageSize) {
//		getUersByName(pageIndex, pageSize);
//	});
	
	$.tbpage("#mainContainer", function (pageIndex, pageSize) {
		getCommentsByAuthor(pageIndex, pageSize);
		_pageSize = pageSize;
	});
   
	// 搜索
	$("#searchNameBtn").click(function() {
		getCommentsByAuthor(0, _pageSize);
	});

	//删除
	$("#mainContainer").on("click",".blog-delete-comment",

		function(){
			var csrfToken=$("meta[name='_csrf']").attr("content");
			var csrfHeader=$("meta[name='_csrf_header']").attr("content");


		    let cid=$(this).attr("commentId");
		    Confirm.show("确定要删除记录吗？",function(){
				$.ajax({
					url: "/comments/"+cid,
					type:'DELETE',
					beforeSend: function(request)
					{
						console.info("haha");
						console.info(csrfToken);
						request.setRequestHeader(csrfHeader,csrfToken);
					},
					success: function(data) {
						if (data.success) {
							Toast.success("操作成功！");
							getCommentsByAuthor(0, _pageSize);
						} else
						{
							Toast.error(data.message);

						}
					},
					error : function() {
						Toast.error("系统错误！");
					}
				});
			});




		});

	// 获取添加用户的界面
	$("#addComment").click(function() {
		$.ajax({
			url: "/comments/add",
			success: function(data){
				$("#commentFormContainer").html(data);
			},
			error : function(data) {
				toastr.error("error!");
			}
		});
	});


	// 提交变更后，清空表单
	$("#submitEdit").click(function() {
		$.ajax({
			url: "/comments",
			type: 'POST',
			data:$('#commentForm').serialize(),
			success: function(data){
				$('#commentForm')[0].reset();

				if (data.success) {
					// 从新刷新主界面
					Toast.success("操作成功！");
					getCommentsByAuthor(0, _pageSize);
				} else {
					Toast.error(data.message);
				}

			},
			error : function() {
				Toast.error("系统错误！");
			}
		});
	});


	// 获取编辑用户的界面
	$("#mainContainer").on("click",".blog-edit-comment", function () {

		$.ajax({
			url: "/comments/edit/" + $(this).attr("commentId"),
			success: function(data){


				$("#commentFormContainer").html(data);
			},
			error : function() {
				Toast.error("error!");
			}
		});
	});






});